package com.gotrade.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author jason.tang
 * @create 2018-12-04 11:48
 * @description 客户端
 */
public class NettyClient {
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup workerGrp = new NioEventLoopGroup();

        bootstrap.group(workerGrp)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    protected void initChannel(Channel channel) throws Exception {
                        /** 指定连接数据读写逻辑 **/
                        // 1. 获取与这条连接相关的逻辑处理链（责任链模式）
                        ChannelPipeline pipeline = channel.pipeline();
                        // 2. 添加一个逻辑处理器(此处理器负责写数据)
                        pipeline.addLast(new FirstClientHandler());
                    }
                });
        bootstrap.connect("localhost", 9099).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("connected success");
            } else {
                System.out.println("connected error");
            }
        });
    }
}